//
//  UIViewController+Tools.m
//  CarCare
//
//  Created by ileo on 14-8-21.
//  Copyright (c) 2014年 baozun. All rights reserved.
//

#import "UIViewController+Inject.h"
#import <objc/runtime.h>
#import "UmengMgr.h"

#define KVCNAME  @"ViewController"

@implementation UIViewController (Inject)

+(void)inject{
    
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        Method oldViewWillDisappear = class_getInstanceMethod(self, @selector(viewWillDisappear:));
        Method newViewWillDisappear = class_getInstanceMethod(self, @selector(_viewWillDisappear:));
        method_exchangeImplementations(oldViewWillDisappear, newViewWillDisappear);
        
        Method oldViewDidAppear = class_getInstanceMethod(self, @selector(viewDidAppear:));
        Method newViewDidAppear = class_getInstanceMethod(self, @selector(_viewDidAppear:));
        method_exchangeImplementations(oldViewDidAppear, newViewDidAppear);
        
    });
}

-(void)_viewDidAppear:(BOOL)animated
{
    
    if (![self isKindOfClass:[UITabBarController class]] && ![self isKindOfClass:[UINavigationController class]] && ![self isKindOfClass:NSClassFromString(@"UIInputWindowController")]) {
        NSString * clazz=[self prefixClassName];
        if (clazz && ![clazz isEqualToString:@"UI"]){
            [MobClick beginLogPageView:clazz];
        }
        [[StatisticsMgr sharedInstance] didAppear:self];
    }

    [self _viewDidAppear:animated];
}

- (void)_viewWillDisappear:(BOOL)animated
{
    if (![self isKindOfClass:[UITabBarController class]] && ![self isKindOfClass:[UINavigationController class]] && ![self isKindOfClass:NSClassFromString(@"UIInputWindowController")]) {
        NSString * clazz=[self prefixClassName];
        if (clazz && ![clazz isEqualToString:@"UI"]){
            [MobClick endLogPageView:clazz];
        }
        
        [[StatisticsMgr sharedInstance] willDisappear:self];
    }
    
    [self _viewWillDisappear:animated];
}

//过滤一下vc，把不需要统计的vc干掉
- (NSString *)prefixClassName
{
    
    NSString * clazz =[NSString stringWithFormat:@"%@",[self class]];
    NSRange range=[clazz rangeOfString:KVCNAME];
    if (range.location==NSNotFound) {
        return nil;
    }
    
//    NSArray *list=@[@"TShopAttentionViewController"];//过滤不要统计的vc
//    for (NSString *item in list) {
//        if ([clazz isEqualToString:item]) {
//            return nil;
//        }
//    }
    
    NSString *name=self.navigationItem.title;
    //去掉ViewController，为了好读
    name=name.length>0?name:[clazz substringToIndex:range.location];
    
    return name;
}
@end
